import {NextRequest, NextResponse} from "next/server";
import {Prisma} from "@prisma/client";
import {addDays, parseISO} from "date-fns";
import db from "@/lib/db";

export const GET = async (req: NextRequest) => {
    const searchParams = req.nextUrl.searchParams;
    // 获取分页参数
    const pageIndex = parseInt(searchParams.get('pageIndex') || '0');
    const pageSize = parseInt(searchParams.get('pageSize') || '10');
    // 计算跳过的记录数
    const skip = pageIndex * pageSize;

    const roleName = searchParams.get("roleName");
    const roleCode = searchParams.get("roleCode");
    const createdAt = searchParams.get("createdAt");

    // 使用分页参数查询用户
    const condition:Prisma.RolesWhereInput={}
    //
    if(roleName){
        Object.assign(
            condition,
            {
                roleName:{
                    contains:roleName
                }
            }
        )
    }
    //
    if(roleCode){
        Object.assign(
            condition,
            {
                roleCode:{
                    contains:roleCode
                }
            }
        )
    }

    if(createdAt){
        const {from, to} = JSON.parse(decodeURIComponent(createdAt));

        const createAtCondition = {};
        if (from) {
            Object.assign(createAtCondition, {
                gte: parseISO(from)
            })
        }

        if (to) {
            Object.assign(createAtCondition, {
                lt: addDays(parseISO(to),1)
            })
        }

        condition.createdAt = createAtCondition;
    }


    const roles = await db.roles.findMany({
        where: condition,
        skip: skip,
        take: pageSize,
    });

    //总数
    const count = await db.roles.count({
        where: condition
    });


    return NextResponse.json({
        code: 200,
        msg: "成功",
        data: {
            // 这里可以替换为实际的总记录数查询
            rowCount: count,
            data: roles,
            pageIndex: pageIndex,
            pageSize: pageSize,
        }
    });
}